package 数组;

import java.util.ArrayList;
import java.util.List;

public class LeetCode986_区间列表的交集 {
    public int[][] intervalIntersection(int[][] firstList, int[][] secondList) {
        if(firstList == null || secondList == null) {
            return new int[0][0];
        }
        List<int[]> list = new ArrayList<>();
        int i = 0;
        int j = 0;
        while(i < firstList.length && j < secondList.length) {
            // 交集区间左端，取他们的较大者
            int first = Math.max(firstList[i][0],secondList[j][0]);
            // 交集区间右端，取他们的较小者
            int end = Math.min(firstList[i][1],secondList[j][1]);
            if(first <= end) {
                list.add(new int[]{first,end});
            }
            if(firstList[i][1] < secondList[j][1]) {
                // 谁先结束，谁的指针就步进
                i++;
            }else {
                j++;
            }
        }
        return list.toArray(new int[0][0]);
    }

}
